# tell/runtime.py
#
#

"""

    W E L C O M E  T O  T E L L !!!

    -=-

    (this code is best enjoyed on a wide screen)

"""

## tell imports

from tell import O, mj
from .callback import Callback
from .plugin import Plugins
from .persist import Persist
from .utils import callstack

## basic imports

import logging
import getpass

## Kernel class

class Kernel(Persist, Plugins):

    """ The kernel holding all the necessary objects. """
        
    def boot(self):
        """ stuff all the needed stuff in a core object and initialise them.  """
        from .task import Dispatcher
        from .utils import resolve_ip, make_datadir, make_plugin, resolve_host, make_opts, hello
        from .log import log_config
        from .plugin import Plugins
        self.name = "kernel"
        self.otype = "runtime"
        opts, args = make_opts()
        if opts.loglevel: loglevel = opts.loglevel
        else: loglevel = "error"
        self.logger = log_config(loglevel)
        if opts.datadir: self.datadir = opts.datadir ; self.prepare()
        self.prepare()
        self.silent = args and "start" not in args 
        if not self.silent: hello()
        if opts.loglevel: logging.warn("B O O T")
        make_datadir(self.root)
        logging.warn("root is %s" % self.root)
        make_plugin(self.root)
        self.run_opts = opts
        self.run_args = args
        self.ip = resolve_ip()
        self.host = resolve_host()
        self.shelluser = getpass.getuser()
        self.shellid = "%s@%s" % (self.shelluser, self.host)
        self.packages = ["tell.plugs", mj(self.root, "plugs")]
        self.dispatcher = Dispatcher()
        self.load_plugs()
        if not args: logging.warn("R E A D Y") ; print(" ")
        return self

    def shutdown(self):
        if not self.run_args: print(" ")
        for bot in self.get_reg("bot"):
            logging.warn("shutting down %s" % bottype)
            try: exit = getattr(bot, "exit")
            except (AttributeError, TypeError): continue
            if exit: exit()

    def put(self, *args, **kwargs):
        args[0].called_from = callstack()
        self.dispatcher.put(*args, **kwargs) 
        return args[0]

    def handle_args(self, *args, **kwargs):
        event = O(**kwargs)
        event.cbtype = "ARGS"
        event.txt = ";" + " ".join(self.run_args)
        event.prepare()
        event.want_dispatch = True
        self.dispatch(event)
        event.display(target=sys.stdout.write)
        sys.stdout.write("\n")
        sys.stdout.flush()
        return event

#### C O M M E N T  -=-  S E C T I O N

""" please write comments on changes you made below, so we can get log of things added/changed. """

## BHJTW 27-11-2012 initial import
